"use strict";

const {
  app: electronApp,
  BrowserWindow,
} = require("electron");
const _ = require("lodash");
const path = require("path");
const CoreWindow = require("ee-core/electron/window");
const {Conf, getConfig} = require("ee-core/config");
const { isProd,getUserHomeDir,getHomeDir, getBaseDir} = require("ee-core/ps");


/**
 * 窗口功能控制器
 * @class
 */
class WindowController {
  
  //关闭窗口
  closeWindow(wcId=1) {
    let win = BrowserWindow.fromId(wcId);
    if (wcId && win) {
      win.close();
      return "success";
    } else{
      let win = CoreWindow.getMainWindow();
      win.close()
      return "No found wcId("+wcId+")!,but MainWindow closed!";
    }
  }
  //最小化窗口
  minimizeWindow(wcId=1) {    
    let win = BrowserWindow.fromId(wcId);
    if (wcId && win) { 
      win.minimize();
      return "success";
    } else { 
      let win = CoreWindow.getMainWindow();
      win.minimize()
      return "No found wcId("+wcId+")!,but MainWindow minimized!";
    }
  }

  //最大化窗口
  expandWindow(wcId=1) {
    let win = BrowserWindow.fromId(wcId);
    if (wcId && win) { 
      win.maximize();
      return "success";
    } else { 
      let win = CoreWindow.getMainWindow();
      win.maximize()
      return "No found wcId("+wcId+")!,but MainWindow maximized!";
    }
  }
    // 登录窗口控制器
  loginWindow(args) {
      const { width, height } = args;      
      const size = {
        width: width || 460,
        height: height || 700,
      };
      const win = CoreWindow.getMainWindow();  
      win.setSize(size.width, size.height);
      win.setResizable(false);
      win.center();
      win.show();
      win.focus();
  }
  
  // 打开主窗口
  mainWindow(args) {
    const { width, height } = args;
    const win = CoreWindow.getMainWindow();
    const size = {
      width: width || 980,
      height: height || 690,
    };
    win.setSize(size.width, size.height);
    win.setResizable(true);
    win.center();
    win.show();
    win.focus();
  }

  /**
   * 恢复窗口
   */
  restoreWindow() {
    const win = CoreWindow.getMainWindow();
    win.restore();
    const bounds = win.getBounds();
    return bounds;
  }

  getAllWindow() {  
    const windows = BrowserWindow.getAllWindows().map(function (item) {
      return { id: item.id, title: item.title };
    });
    return CoreWindow.getMainWindow().id, windows;
  }
  /**
   * 打开新窗口
   */
  createWindow(args) {

    const { type, content, windowName, windowTitle, isModal } = args;

    let contentUrl = null;
    if (type == "html") {
      contentUrl = path.join("file://", electronApp.getAppPath(), content);
    } else if (type == "web") {
      contentUrl = content;
    } else if (type == "vue") {
      let addr ="http://localhost:8081";
      if ( isProd()) {
        const mainServer = Conf.getValue("mainServer");
        if (Conf.isFileProtocol(mainServer)) {
          addr =
            mainServer.protocol +
            path.join(getHomeDir(), mainServer.indexPath);
        } else {
          addr = mainServer.protocol + mainServer.host + ":" + mainServer.port;
        }
      }
      contentUrl = addr + content;
    } else {
      return false;
    }

    let opt = {
      icon: path.join(getUserHomeDir(), "public","images","logo-32.png"),
      title: windowTitle,
      width: args.windowWidth || "",
      height: args.windowHeight || "",
      x: args.windowX || Math.floor(Math.random()*400),
      y: args.windowY || Math.floor(Math.random()*200),
      frame: args.windowFrame || true, // 默认无边框
      resizable: args.resizable || false,
      autoHideMenuBar: args.windowHideMenuBar || false, // 隐藏菜单栏，默认为false
      titleBarStyle: args.windowTitleBarStyle || "default",
      titleBarOverlay: args.windowTitleBarOverlay || false,//隐藏标题栏后悬浮按钮
      closable: args.windowClosable || true,
      alwaysOnTop : args.windowAlwaysOnTop || false //窗口置顶
      
    };
    if(args.isExternal){
      opt.webPreferences = {
        nodeIntegration: true,
        contextIsolation: true,
        preload: path.join( getBaseDir(), 'preload', 'bridge.js'),
      };
    }
    if (isModal) {
      opt.modal = true;
      opt.parent = CoreWindow.getMainWindow();
    }
    
    const win = new BrowserWindow(opt);
    const winWcId = win.webContents.id;

    win.loadURL(contentUrl);
    win.once("ready-to-show", () => {
      if(args.isCenter) { 
        // win.center();
      }
      win.setTitle(windowTitle);
      win.focus();
      win.show();
    });
    return winWcId;
  }
  /**
   * 获取窗口contents id
   */
  getWCid(args) {
    // 主窗口的name默认是main，其它窗口name开发者自己定义
    const name = args;
    const id = Addon.get("window").getWCid(name);
    return id;
  }

  //创建设置窗口
  openSettingWindow(args) {
    const { content } = args;

    let opt = {
        icon: path.join(getUserHomeDir(), "public/images/logo-32.png"),
        title: "设置",
        width: args.width||800,
        height: args.height||600,
        frame: false,   // 无边框
        resizable: false,
        // 隐藏菜单栏，默认为false
        autoHideMenuBar: true, 
        titleBarStyle: "hidden",
        //隐藏标题栏后悬浮按钮||false
        titleBarOverlay:  { color:'#dddddd',symbolColor:'#000000',height: 26},
        closable: true,
        // modal: false, //是否开启模态
        // parent : CoreWindow.getMainWindow(),//是否开启模态
        // alwaysOnTop : true ,//窗口置顶
        webPreferences : {
          contextIsolation: true,
          preload: path.join( getBaseDir(), 'preload', 'bridge.js'),
        }
      }
      
      const win = new BrowserWindow(opt);
      const winWcId = win.webContents.id;
  
      win.loadURL( "http://localhost:8081/#"+content,{type:'vue'});
      win.once("ready-to-show", () => {
        win.setTitle(opt.title);        
        win.focus();
        win.show();        
      });
      // 打开开发者工具
      // win.webContents.openDevTools(); 
      return winWcId;
  }

  /**
   * 获取窗口contents id
   */
  getWCid(args) {
    // 主窗口的name默认是main，其它窗口name开发者自己定义
    const name = args;
    const id = Addon.get("window").getWCid(name);
    return id;
  }

}

WindowController.toString = () => "[class WindowController]";
module.exports = WindowController;
